using UnityEngine;
using System.Collections;

public class TractorBeam : MonoBehaviour
{
    public Transform tractorObject;
    public float tractorDistance;

    private float currentGunRotation;
	private float currentBlockRotation;
	private GameObject theGunRotator;

    // Use this for initialization
	void Start()
    {
		theGunRotator = GameObject.FindGameObjectWithTag("GunRotator");
    }

    // Update is called once per frame
    void Update()
    {
		currentGunRotation = theGunRotator.transform.localRotation.z;

        if (tractorObject)
        {
            Vector3 objectPos = transform.position + transform.forward * tractorDistance;
            objectPos.y = 0;
            tractorObject.position = Vector3.Lerp(tractorObject.position, objectPos, 5.0f * Time.deltaTime);
        }

        if(DataManager.Instance.haveBlock && Input.GetKeyDown(KeyCode.E))
		{
			Debug.Log("rotate block");
			currentBlockRotation += 90;
			if(currentBlockRotation == 360)
				currentBlockRotation = 0;
			
			tractorObject.transform.rotation = Quaternion.Euler(0, currentBlockRotation, 0);
		}

        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            if (tractorObject)
            {
                BlockController blockscript = tractorObject.GetComponent<BlockController>();
                blockscript.LocalPickedUp = false;
                if (blockscript.Shoot(transform.forward))
                    tractorObject = null;
				DataManager.Instance.haveBlock = false;
            }
        }

        if (Input.GetKeyDown(KeyCode.Mouse1))
        {
            if (!tractorObject)
            {
                foreach (RaycastHit hit in Physics.RaycastAll(transform.position, transform.forward, 30))
                {
                    if (hit.collider.gameObject.CompareTag("block"))
                    {
                        tractorObject = hit.collider.transform.parent;

                        BlockController blockscript = tractorObject.GetComponent<BlockController>();
                        if (blockscript.PickedUp)
                        {
                            tractorObject = null;
                        }
                        else
                        {
                            blockscript.Moving = false;
                            blockscript.PickedUp = true;
                            blockscript.LocalPickedUp = true;
                        }
                        DataManager.Instance.haveBlock = true;
                    }
                }
            }
            else
            {
                BlockController blockscript = tractorObject.GetComponent<BlockController>();
                blockscript.LocalPickedUp = false;
                blockscript.PickedUp = false;
                tractorObject = null;
            }
        }
    }
}
